<route lang="json5">
{
  style: {
    navigationBarTitleText: '编辑资料'
  }
}
</route>

<script lang="ts" setup>
import dayjs from 'dayjs'
import { ref, onMounted, computed } from 'vue'
import { useSupabaseCoupleStore } from '@/store/supabaseCouple'
import { userService } from '@/services/supabase'

const coupleStore = useSupabaseCoupleStore()
const form = ref({
  coverImage: '',
  user1Name: '',
  user2Name: '',
  relationshipStart: '',
  story: '',
})

const tempRelationshipStart = ref(Date.now())
const showDatePicker = ref(false)

function chooseCover() {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    success: (res) => {
      // #ifdef H5
      // H5 环境：使用 FileReader 将 File 对象转换为 Base64
      const reader = new FileReader()
      reader.onload = (e) => {
        form.value.coverImage = e.target.result as string
      }
      reader.onerror = (err) => {
        uni.showToast({ title: '图片转换失败', icon: 'error' })
        console.error('FileReader error:', err)
      }
      reader.readAsDataURL(res.tempFiles[0] as unknown as Blob)
      // #endif

      // #ifndef H5
      // 小程序/App 环境：使用 getFileSystemManager
      const tempFilePath = res.tempFilePaths[0]
      uni.getFileSystemManager().readFile({
        filePath: tempFilePath,
        encoding: 'base64',
        success: (result) => {
          form.value.coverImage = `data:image/jpeg;base64,${result.data}`
        },
        fail: (err) => {
          uni.showToast({ title: '图片转换失败', icon: 'error' })
          console.error('readFile failed:', err)
        },
      })
      // #endif
    },
    fail: (err) => {
      uni.showToast({ title: '选择图片失败', icon: 'none' })
      console.log('chooseImage fail', err)
    },
  })
}

const displayDate = computed(() => dayjs(tempRelationshipStart.value).format('YYYY-MM-DD'))

function handleDateConfirm() {
  form.value.relationshipStart = dayjs(tempRelationshipStart.value).format('YYYY-MM-DD')
  showDatePicker.value = false
}

async function save() {
  try {
    // 1) 处理封面上传
    const coverUrl = form.value.coverImage
    // 仅存入本地，不上送接口
    if (coverUrl) {
      uni.setStorageSync('cover_image_local', coverUrl)
    }

    // 2) 更新 users 表的昵称（有值才更新）
    const u1Id = coupleStore.profile?.user1.id
    const u2Id = coupleStore.profile?.user2.id
    if (u1Id && form.value.user1Name && form.value.user1Name !== coupleStore.profile?.user1.name) {
      await userService.update(u1Id, { name: form.value.user1Name })
    }
    if (u2Id && form.value.user2Name && form.value.user2Name !== coupleStore.profile?.user2.name) {
      await userService.update(u2Id, { name: form.value.user2Name })
    }

    // 3) 更新 couple_profiles 表中其余字段（仅 story/relationship_start，封面不再上传）
    await coupleStore.updateProfile({
      relationshipStart: form.value.relationshipStart,
      story: form.value.story,
    } as any)

    // 4) 重新拉取（封面来自本地存储，这里不会被接口覆盖）
    await coupleStore.initProfile()
    // 保存后回显依然以本地封面为准
    form.value.coverImage = uni.getStorageSync('cover_image_local') || coupleStore.profile?.coverImage || ''
    uni.showToast({ title: '已保存', icon: 'success' })
    setTimeout(() => uni.navigateBack(), 500)
  }
  catch (e) {
    uni.showToast({ title: '保存失败，请重试', icon: 'none' })
  }
}

onMounted(() => {
  coupleStore.initProfile().then(() => {
    form.value = {
      // 从本地存储加载封面图片
      coverImage: uni.getStorageSync('cover_image_local') || coupleStore.profile?.coverImage || '',
      user1Name: coupleStore.profile?.user1.name || '',
      user2Name: coupleStore.profile?.user2.name || '',
      relationshipStart: coupleStore.profile?.relationshipStart || '',
      story: coupleStore.profile?.story || '',
    }
    // 同步日期选择器的初始值
    if (form.value.relationshipStart) {
      tempRelationshipStart.value = dayjs(form.value.relationshipStart).valueOf()
    }
  })
})
</script>

<template>
  <view class="edit-container">
    <view class="section">
      <view class="label">
        封面
      </view>
      <view class="cover" @click="chooseCover">
        <image v-if="form.coverImage" :src="form.coverImage" class="cover-img" mode="aspectFill" />
        <view v-else class="cover-ph">
          点击选择封面
        </view>
      </view>
    </view>

    <wd-cell-group>
      <wd-input v-model="form.user1Name" label="Ta的昵称" placeholder="输入昵称" />
      <wd-input v-model="form.user2Name" label="我的昵称" placeholder="输入昵称" />
      <wd-cell title="相恋日" :value="displayDate || '请选择日期'" is-link @click="showDatePicker = true" />
    </wd-cell-group>

    <view class="section">
      <view class="label">
        我们的故事
      </view>
      <wd-textarea v-model="form.story" placeholder="写点你们的故事吧…" :auto-height="true" />
    </view>

    <view class="actions">
      <wd-button type="primary" block @click="save">
        保存
      </wd-button>
    </view>

    <!-- 日期选择器 -->
    <wd-popup v-model="showDatePicker" position="bottom">
      <wd-datetime-picker-view
        v-model="tempRelationshipStart"
        type="date"
      />
      <view class="picker-actions">
        <wd-button @click="showDatePicker = false">
          取消
        </wd-button>
        <wd-button type="primary" @click="handleDateConfirm">
          确定
        </wd-button>
      </view>
    </wd-popup>
  </view>
</template>

<style scoped lang="scss">
.edit-container {
  min-height: 100vh;
  background-color: #fff0f5;
  background-image: radial-gradient(circle at 25% 25%, rgba(255, 228, 225, 0.4) 2px, transparent 0),
    radial-gradient(circle at 75% 75%, rgba(255, 228, 225, 0.4) 2px, transparent 0);
  background-size: 20px 20px;
  padding: 16px;
}

.card-base {
  background: #ffffff;
  border-radius: 24px;
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: 0 4px 16px rgba(255, 105, 180, 0.1), 0 10px 30px rgba(255, 105, 180, 0.15);
  border: 1px solid white;
}

.section {
  @extend .card-base;
}

.label {
  font-size: 16px;
  font-weight: bold;
  color: #444;
  margin-bottom: 12px;
}

.cover {
  height: 160px;
  border-radius: 20px;
  background: #fffafa;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  border: 2px dashed #ffdde5;
}

.cover-img {
  width: 100%;
  height: 100%;
}

.cover-ph {
  color: #ff87ab;
  font-size: 14px;
  font-weight: 600;
}

.actions {
  padding: 16px;
}

.picker-actions {
  display: flex;
  gap: 12px;
  padding: 16px;
  background: white;
  border-top: 1px solid #f5f5f5;
}
</style>
